package com.tramp.controller;

import com.tramp.frame.config.BaseConfig;
import com.tramp.frame.server.base.ResultData;
import com.tramp.frame.server.exception.GenericException;
import com.tramp.utils.DateUtil;
import com.tramp.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * Created by chen on 2017/10/22.
 */
@Controller
@RequestMapping("/common/")
public class CommonController {

    @Autowired
    private BaseConfig baseConfig;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ResponseBody
    public ResultData upload(@RequestPart @RequestParam("file") MultipartFile file) {
        // 保存的位置
        String path = baseConfig.getUploadPath() + "/" + DateUtil.getNowdateYYYYMMDD();
        //文件后缀
        String suffix = StringUtils.isNotBlank(file.getOriginalFilename()) ? file.getOriginalFilename() : "";
        String[] suff = suffix.split("\\.");
        String filename = String.valueOf(System.currentTimeMillis());
        if (suff.length > 1) {
            filename += "." + suff[suff.length - 1];
        }
        try {
            InputStream sbs = file.getInputStream();
            FileUtil.saveFileFromInputStream(sbs, path, filename);
        } catch (Exception e) {
            throw new GenericException("上传文件失败");
        }
        return ResultData.success(path + "/" + filename);
    }

    /**
     * 跳转到404页面
     */
    @RequestMapping(path = "error")
    public String errorPage() {
        return "404";
    }
}
